<script>
  import TreeSelect from '@/components/common/tree-select';

  export default {
    name: 'multi-dict-dialog',
    components: {
      TreeSelect
    },
    data() {
      return {
        // 弹出框显示状态[true-显示 false-隐藏]
        visible: false,
        // 弹出框标题
        title: undefined,
        // 操作类型[true-修改 false-添加]
        optType: false,
        // 级联字典表单对象
        multiDictForm: {
          // 主键
          id: undefined,
          // 父级主键
          parentId: undefined,
          // 父级路径
          parentPath: '',
          // 类型
          type: undefined,
          // 名称
          name: '',
          // 字符串值
          stringValue: '',
          // 排序等级
          sort: undefined,
          // 默认状态[0-是 1-否]
          defaultStatus: 1,
        },
        // 级联字典树
        multiDictTree: [],
        // 类型枚举列表
        typeEnumList: [],
        // 级联字典表单校验规则对象
        multiDictRules: {
          parentId: [
            { required: true, message: '父级字典不能为空', trigger: 'change' }
          ],
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '类型不能为空', trigger: 'blur' }
          ],
          stringValue: [
            { required: true, message: '字典值不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '排序等级不能为空', trigger: 'blur' },
            { type: 'number', message: '排序等级必须为数字值'}
          ],
          defaultStatus: [
            { required: true, message: '默认状态不能为空', trigger: 'blur' }
          ],
        },
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false
      }
    },
    methods: {
      /**
       * 打开弹出框方法
       * @param {boolean} optType         操作类型[true-修改 false-添加]
       * @param {Object}  multiDict       级联字典对象
       * @param {Object}  parentMultiDict 父级级联字典对象
       */
      openDialog(optType, multiDict, parentMultiDict) {
        this.visible = true;
        this.optType = optType;
        this.title = optType ? '修改级联字典' : '添加级联字典';
        const isSave = multiDict == null;

        const multiDictForm = this.multiDictForm;
        multiDictForm.parentId = '0';
        if (parentMultiDict) {
          multiDictForm.parentId = parentMultiDict.id;
          multiDictForm.parentPath = parentMultiDict.parentPath;
          multiDictForm.type = parentMultiDict.type;
        }
        if (!isSave) {
          for (let propKey in multiDictForm) {
            if (multiDict.hasOwnProperty(propKey)) {
              multiDictForm[propKey] = multiDict[propKey];
            }
          }
        }

        this.getMultiDictEnum(isSave ? undefined : multiDict.id);
        if (isSave) {
          this.getNextSort(multiDictForm.parentId);
        }
      },
      /**
       * 获取级联字典枚举方法
       * @param {string} id       主键
       */
      getMultiDictEnum(id) {
        this.$axios.$get('/multi-dict/enums', { params: { id }})
          .then(({ data }) => {
            this.multiDictTree = data.multiDictTree;
            this.typeEnumList = data.typeEnumList;
          })
          .catch(() => {});
      },
      /**
       * 获取下一个排序等级方法
       * @param {string} parentId 父级主键
       */
      getNextSort(parentId) {
        this.$axios.$get('/multi-dict/next/sort', { params: { parentId }})
          .then(({ data }) => {
            this.multiDictForm.sort = data;
          })
          .catch(() => {});
      },
      /**
       * 提交事件
       */
      submitHandle() {
        if (this.optType) {
          this.updateHandle();
        } else {
          this.saveHandle();
        }
      },
      /**
       * 新增事件
       */
      saveHandle() {
        this.$refs.multiDictForm.validate()
          .then(() => {
            this.buttonLoad = true;

            return this.$axios.$post('/multi-dict/save', this.multiDictForm);
          })
          .then(() => {
            this.notify('success', '操作成功', '添加级联字典成功');

            this.closeDialog(true);
          })
          .catch(() => {})
          .finally(() => {
            this.buttonLoad = false;
          });
      },
      /**
       * 修改事件
       */
      updateHandle() {
        this.$refs.multiDictForm.validate()
          .then(() => {
            this.buttonLoad = true;

            return this.$axios.$post('/multi-dict/update', this.multiDictForm);
          })
          .then(() => {
            this.notify('success', '操作成功', '修改级联字典成功');

            this.closeDialog(true);
          })
          .catch(() => {})
          .finally(() => {
            this.buttonLoad = false;
          });
      },
      /**
       * 选中父级节点事件
       * @param {Object} node 父级节点对象
       */
      changeParentMultiDictHandle(node) {
        const multiDictForm = this.multiDictForm;
        multiDictForm.parentId = node.id;
        multiDictForm.parentPath = node.parentPath;
        multiDictForm.type = node.type;
      },
      /**
       * 关闭弹出框方法
       * @param {boolean | function} refresh 是否刷新父级组件数据
       */
      closeDialog(refresh) {
        // 重置表单
        this.$refs.multiDictForm.resetFields();
        this.multiDictForm.id = undefined;
        this.multiDictForm.parentPath = '';
        this.multiDictTree = [];
        this.typeEnumList = [];

        if (typeof refresh === 'function') {
          refresh = false;
        }
        if (refresh) {
          // 向上传递事件
          this.$emit('refresh');
        }
        this.$nextTick(() => {
          // 关闭弹出框
          this.visible = false;
        });
      }
    }
  }
</script>

<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="45%"
    top="10vh"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    class="multi-dict-dialog"
  >
    <el-form size="small" :model="multiDictForm" :rules="multiDictRules" status-icon label-width="100px"
             @keyup.enter.native="submitHandle" ref="multiDictForm">
      <el-form-item label="父级字典" prop="parentId">
        <tree-select :data-obj="multiDictForm" prop-key="parentId" node-key="id" :tree-data="multiDictTree"
                     placeholder="请选择父级字典" class-name="width90percent"
                     @node-click="changeParentMultiDictHandle" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="multiDictForm.type" :disabled="!!multiDictForm.parentId && multiDictForm.parentId !== '0'"
                   clearable placeholder="请选择类型" class="width90percent">
          <el-option v-for="typeEnum in typeEnumList" :key="'typeEnum' + typeEnum.value" :label="typeEnum.name"
                     :value="typeEnum.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="multiDictForm.name"
                  clearable
                  maxlength="50"
                  show-word-limit
                  placeholder="请输入名称"
                  class="width90percent">
        </el-input>
      </el-form-item>
      <el-form-item label="值" prop="stringValue">
        <el-input v-model="multiDictForm.stringValue"
                  clearable
                  maxlength="200"
                  show-word-limit
                  placeholder="请输入名称"
                  class="width90percent">
        </el-input>
      </el-form-item>
      <el-form-item label="排序等级" prop="sort">
        <el-input v-model="multiDictForm.sort"
                  clearable
                  maxlength="5"
                  show-word-limit
                  placeholder="请输入序号"
                  class="width90percent">
        </el-input>
      </el-form-item>
      <el-form-item label="是否默认" prop="defaultStatus">
        <el-radio-group v-model="multiDictForm.defaultStatus">
          <el-radio :label="0" border>是</el-radio>
          <el-radio :label="1" border>否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="closeDialog(false)">取 消</el-button>
      <el-button v-show="!optType" :disabled="buttonLoad" type="primary" @click="saveHandle">添 加</el-button>
      <el-button v-show="optType" :disabled="buttonLoad" type="primary"  @click="updateHandle">修 改</el-button>
    </span>
  </el-dialog>
</template>

<style scoped>
  .multi-dict-dialog >>> .width90percent {
    width: 90%;
  }
</style>
